<template>
  <div class="wallet-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card>
          <div slot="header" class="card-header">
            <span>钱包管理</span>
            <div v-if="hasWallet" class="network-selector">
              <span>当前网络:</span>
              <el-select
                v-model="currentNetwork"
                @change="switchNetwork"
                size="small"
              >
                <el-option
                  v-for="network in networks"
                  :key="network.id"
                  :label="network.name"
                  :value="network.id"
                >
                </el-option>
              </el-select>
            </div>
          </div>

          <div v-if="!hasWallet" class="bind-wallet-section">
            <h3>绑定钱包地址</h3>
            <p>请选择绑定钱包的方式</p>

            <el-tabs v-model="activeTab">
              <el-tab-pane label="手动输入" name="manual">
                <el-form
                  :model="bindForm"
                  :rules="bindRules"
                  ref="bindForm"
                  label-width="100px"
                >
                  <el-form-item label="钱包地址" prop="walletAddress">
                    <el-input
                      v-model="bindForm.walletAddress"
                      placeholder="请输入以太坊钱包地址"
                    ></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button
                      type="primary"
                      @click="bindWalletManual"
                      :loading="loading"
                      >绑定钱包</el-button
                    >
                  </el-form-item>
                </el-form>
              </el-tab-pane>
              <el-tab-pane label="连接MetaMask" name="metamask">
                <div class="metamask-section">
                  <div
                    v-if="!isMetaMaskInstalled"
                    class="metamask-not-installed"
                  >
                    <p>您尚未安装MetaMask钱包插件</p>
                    <el-button type="primary" @click="goToMetaMaskSite">
                      安装MetaMask
                    </el-button>
                  </div>
                  <div v-else class="metamask-connect">
                    <p>点击下方按钮连接MetaMask钱包</p>
                    <el-button
                      type="primary"
                      @click="connectWithMetaMask"
                      :loading="metamaskLoading"
                    >
                      连接MetaMask
                    </el-button>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>

          <div v-else class="wallet-info-section">
            <h3>钱包信息</h3>
            <el-descriptions border>
              <el-descriptions-item label="钱包地址">
                <el-tag type="success">{{ walletAddress }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item
                :label="`${nativeSymbol || 'ETH'}余额`"
                v-if="balance"
              >
                {{ balance }} {{ nativeSymbol || "ETH" }}
              </el-descriptions-item>
              <el-descriptions-item label="平台余额">
                {{ userBalance }} 单位
              </el-descriptions-item>
            </el-descriptions>

            <div class="deposit-section" style="margin-top: 20px">
              <h3>充值余额</h3>
              <el-form :inline="true" :model="depositForm" class="deposit-form">
                <el-form-item label="充值金额">
                  <el-input-number
                    v-model="depositForm.amount"
                    :min="1"
                    :step="10"
                  ></el-input-number>
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="primary"
                    @click="handleDeposit"
                    :loading="depositLoading"
                    >充值</el-button
                  >
                </el-form-item>
              </el-form>
            </div>

            <div class="wallet-assets" v-if="assets && assets.length > 0">
              <h3>我的资产</h3>
              <el-table :data="assets" style="width: 100%">
                <el-table-column prop="asset_type" label="资产类型">
                  <template slot-scope="scope">
                    <el-tag
                      :type="
                        scope.row.asset_type === 'token' ? 'primary' : 'success'
                      "
                    >
                      {{ scope.row.asset_type === "token" ? "代币" : "NFT" }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="token_symbol"
                  label="代币符号"
                ></el-table-column>
                <el-table-column
                  prop="token_address"
                  label="合约地址"
                  width="220"
                >
                  <template slot-scope="scope">
                    <el-tooltip
                      :content="scope.row.token_address"
                      placement="top"
                    >
                      <span>{{
                        scope.row.token_address | truncateAddress
                      }}</span>
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column prop="token_id" label="Token ID">
                  <template slot-scope="scope">
                    <span v-if="scope.row.asset_type === 'nft'">{{
                      scope.row.token_id
                    }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="balance" label="余额">
                  <template slot-scope="scope">
                    <span v-if="scope.row.asset_type === 'token'">{{
                      scope.row.balance
                    }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div v-else class="no-assets">
              <p>暂无资产</p>
            </div>

            <el-button
              type="primary"
              @click="refreshWalletInfo"
              :loading="loading"
              style="margin-top: 20px"
            >
              刷新钱包信息
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapGetters, mapActions } from "vuex";
import walletUtils from "../utils/wallet";
import {
  getNetworkList,
  switchNetwork as switchMetaMaskNetwork,
} from "@/const/Networks";

export default {
  name: "Wallet",
  data() {
    return {
      activeTab: "manual",
      bindForm: {
        walletAddress: "",
      },
      networks: [],
      currentNetwork: "ethereum",
      bindRules: {
        walletAddress: [
          { required: true, message: "请输入钱包地址", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback();
                return;
              }
              if (!walletUtils.isValidAddress(value)) {
                callback(new Error("请输入有效的以太坊钱包地址"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
      loading: false,
      metamaskLoading: false,
      depositLoading: false,
      isMetaMaskInstalled: false,
      balance: null,
      userBalance: 0,
      assets: [],
      depositForm: {
        amount: 10,
      },
    };
  },
  computed: {
    ...mapGetters(["walletAddress", "hasWallet"]),
  },
  filters: {
    truncateAddress(address) {
      if (!address) return "";
      return address.slice(0, 6) + "..." + address.slice(-4);
    },
  },
  methods: {
    ...mapActions([
      "bindWallet",
      "getWalletInfo",
      "getWalletBalance",
      "depositBalance",
    ]),

    // 获取支持的网络列表
    async fetchNetworks() {
      try {
        const response = await axios.get("/api/wallet/networks");
        this.networks = response.data;
      } catch (error) {
        console.error("获取网络列表失败:", error);
        this.$message.error("获取网络列表失败");
      }
    },

    // 切换网络
    async switchNetwork(networkId) {
      try {
        this.loading = true;

        // 1. 切换MetaMask网络
        if (walletUtils.isMetaMaskInstalled()) {
          await switchMetaMaskNetwork(networkId);
        }

        // 2. 更新服务器端用户当前网络
        await axios.post("/api/wallet/switch-network", {
          network_id: networkId,
        });

        // 3. 刷新钱包信息
        await this.refreshWalletInfo();

        this.$message.success(
          `已切换到${this.networks.find((n) => n.id === networkId).name}网络`
        );
      } catch (error) {
        console.error("切换网络失败:", error);
        this.$message.error(error.message || "切换网络失败");
      } finally {
        this.loading = false;
      }
    },
    async bindWalletManual() {
      try {
        this.$refs.bindForm.validate(async (valid) => {
          if (valid) {
            this.loading = true;
            await this.bindWallet(this.bindForm.walletAddress);
            await this.getWalletInfo();
            this.$message.success("钱包绑定成功");
          }
        });
      } catch (error) {
        this.$message.error(error.response?.data?.message || "绑定钱包失败");
      } finally {
        this.loading = false;
      }
    },

    // 连接MetaMask钱包
    async connectWithMetaMask() {
      try {
        this.metamaskLoading = true;
        const address = await walletUtils.connectMetaMask();
        if (address) {
          await this.bindWallet(address);
          await this.getWalletInfo();
          this.$message.success("MetaMask钱包绑定成功");
        }
      } catch (error) {
        this.$message.error(error.message || "连接MetaMask失败");
      } finally {
        this.metamaskLoading = false;
      }
    },

    // 跳转到MetaMask官网
    goToMetaMaskSite() {
      window.open("https://metamask.io/download/", "_blank");
    },
    async refreshWalletInfo() {
      try {
        this.loading = true;
        const walletInfo = await this.getWalletInfo();
        this.assets = walletInfo.assets || [];
        this.userBalance = walletInfo.balance || 0;

        const balanceResponse = await axios.get("/api/wallet/balance");
        this.balance = balanceResponse.data.native_balance;
        this.nativeSymbol = balanceResponse.data.native_symbol;
        this.currentNetwork = balanceResponse.data.network.id || "ethereum";

        this.$message.success("钱包信息已更新");
      } catch (error) {
        this.$message.error(
          error.response?.data?.message || "获取钱包信息失败"
        );
      } finally {
        this.loading = false;
      }
    },

    async handleDeposit() {
      try {
        this.depositLoading = true;
        const response = await this.depositBalance(this.depositForm.amount);
        this.userBalance = response.balance;
        this.$message.success("充值成功");
      } catch (error) {
        this.$message.error(error.response?.data?.message || "充值失败");
      } finally {
        this.depositLoading = false;
      }
    },
  },
  async created() {
    // 检查是否安装了MetaMask
    this.isMetaMaskInstalled = walletUtils.isMetaMaskInstalled();

    // 获取支持的网络列表
    this.fetchNetworks();

    // 获取钱包信息
    if (this.hasWallet) {
      await this.refreshWalletInfo();
    } else {
      await this.getWalletInfo();

      // 如果安装了MetaMask，尝试获取当前连接的地址
      if (this.isMetaMaskInstalled) {
        const address = await walletUtils.getCurrentAddress();
        if (address) {
          this.bindForm.walletAddress = address;
        }
      }
    }

    // 监听MetaMask账户变化
    walletUtils.onAccountsChanged((accounts) => {
      if (accounts.length > 0) {
        this.bindForm.walletAddress = accounts[0];
      }
    });

    // 监听MetaMask网络变化
    walletUtils.onChainChanged(async (chainId) => {
      console.log("MetaMask网络已切换:", chainId);
      // 获取当前网络ID
      const networkId = await walletUtils.getCurrentNetworkId();
      this.currentNetwork = networkId;

      // 如果已绑定钱包，刷新钱包信息
      if (this.hasWallet) {
        this.refreshWalletInfo();
      }
    });
  },
};
</script>

<style scoped>
.wallet-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.network-selector {
  display: flex;
  align-items: center;
}

.network-selector span {
  margin-right: 10px;
  font-size: 14px;
}

.bind-wallet-section,
.wallet-info-section {
  margin-top: 20px;
}

.metamask-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  text-align: center;
}

.metamask-not-installed,
.metamask-connect {
  margin: 20px 0;
}

.el-tabs {
  margin-top: 20px;
}

.no-assets {
  margin: 20px 0;
  text-align: center;
  color: #909399;
}
</style>
